package com.kaikai.edu.filter;

import com.alibaba.excel.util.StringUtils;
import com.kaikai.commonutils.JwtUtils;
import com.kaikai.edu.entity.EduUser;
import com.kaikai.edu.service.EduLoginService;
import com.kaikai.edu.service.EduUserService;
import com.kaikai.edu.utils.RedisUtil;
import com.kaikai.servicebase.exceptionhandler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author yujiankai
 * @Description 权限拦截器
 * @date 2021/12/1 14:53
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private EduUserService userService;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws InterruptedException, IOException {
        //放行登录请求
        if (request.getRequestURI().contains("/user/login")) {
            return true;
        }
        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        //取出请求头中的token
        String token = request.getHeader("token");
        System.out.println("token: " + token);
        if (StringUtils.isEmpty(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //解析token
        try {
            if (JwtUtils.checkToken(token)) {
                String userId = JwtUtils.getMemberIdByJwtToken(request);
                //判断是否和redis中对应
                String redisToken = (String) redisUtil.get("token" + userId);
                if (Objects.equals(redisToken, token)) {
                    return true;
                }
                throw new MyException(4000, "账号已在别处登录");
            }
            return false;
        }catch(Exception e){
            throw new MyException(4000, "登录失效");
        }
    }
}
